﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PeerJoinWebService
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Context.Response.ContentType = "text/plain";
            if (Context.Request.HttpMethod == "POST")
            {
                StringBuilder entry = new StringBuilder();
                string[] lines = new string[4];
                var reader = new StreamReader(Context.Request.InputStream);
                for (int i = 0; i < lines.Length; i++)
                {
                    lines[i] = reader.ReadLine();
                    if (i != 3)
                        entry.Append(lines[i] + " ");
                    else
                        entry.Append(Convert.ToBase64String(Encoding.UTF8.GetBytes(lines[i])) + " ");
                }

                int port; IPAddress ip; long time;
                if (IPAddress.TryParse(lines[0], out ip) && int.TryParse(lines[1], out port) && long.TryParse(lines[2], out time))
                {
                    string filepath = Path.Combine(Context.Server.MapPath("~/JoinLog"), DateTime.Now.ToString("dd-MM-yy") + ".txt");
                    FileStream fs = File.Exists(filepath) ? File.Open(filepath, FileMode.Append) : File.Open(filepath, FileMode.Create);
                    StreamWriter writer = new StreamWriter(fs);
                    writer.WriteLine(entry.ToString());
                    writer.Close();
                    fs.Close();
                    Context.Response.Write("OK");
                    return;
                }
            }
            Context.Response.Write("ERROR");
        }
    }
}